// pages/pointsMall/pointsMall.js
import {
    ajaxPost,
    showToast,
    formatTime
} from '../../../utils/util'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        navList: [{
            icon: "https://ruiyuanhui.3todo.com/uploads/img/my-score-img.png",
            text: "我的积分",
            url: "/pages/scoresMall/myScores/myScores",
            img: 'https://ruiyuanhui.3todo.com/uploads/img/my-score-icon.png'
        }, {
            icon: "https://ruiyuanhui.3todo.com/uploads/img/get-score-img.png",
            text: "获得积分",
            url: "/pages/scoresMall/getScores/getScores",
            img: 'https://ruiyuanhui.3todo.com/uploads/img/get-score-icon.png'
        }],
        tabList: [],
        currentTab: 0,
        isExchange: true,
        isLogin: true,
        noGet: false,
        hotGoods: [],
        timeGoods: [],
        page: 1,
        swiperCurrent: 0,
        limit: 10,
        isTop: false,
        jinyong: true,
        scroll_left: '',
        currentIndex: 0,
        id: 0,
        timestamp: 0,
        actEndTimeList:[]
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {

        
    },


    onReady() {


    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        var tmp = Date.parse(new Date()).toString();
        tmp = tmp.substr(0, 10);
        this.setData({
            timestamp: Number(tmp)
        })
        console.log(this.data.timestamp)
        wx.showLoading({
            title: '加载中...'
        })

        var token = wx.getStorageSync("token")
        if (token) {
            this.setData({
                isLogin: true
            })
        }
        this.getCateChangeList()
        this.getDataList()
        if (token) {
            ajaxPost('member/index', {}, res => {
                if (res.code == 60000) {
                    wx.removeStorageSync('token')
                    return
                }
            })
        }
    },


    // getIndexData() {
    //     ajaxPost('index/index', {}, res => {
    //         var data = res.data
    //         this.setData({
    //             bannerUrls: data.mall_album,
    //             newsList: data.news,
    //             goodsList: data.goods
    //         })
    //     })
    // },
    /**
     * 跳转商品详情
     * @param {*} e 
     */
    navGoodDetail(e) {
        wx.navigateTo({
            url: '/pages/scoresMall/good_detail/good_detail?id=' + e.currentTarget.dataset.id,
        });
    },
    /**
     * 跳转兑换
     * @param {*} e 
     */
    navExchange() {
        var token = wx.getStorageSync("token");
        if (!token) {
            this.setData({
                isLogin: false
            })
            return
        } else {
            wx.navigateTo({
                url: '/pages/index/scoreExchange/scoreExchange'
            })
        }
    },
    /**
     * 暂不登录
     * @param {*} e 
     */
    noLogin() {
        this.setData({
            isLogin: true
        })
    },
    /**
     * 跳转引导页
     * @param {*} e 
     */
    navGuide() {
        wx.navigateTo({
            url: '/pages/guide/guide'
        })
    },
    //切换tab
    changeTab(e) {
        wx.showLoading({
            title: '加载中...'
        })
        this.setData({
            currentTab: e.currentTarget.dataset.index,
            id: e.currentTarget.dataset.id
        })
        this.getCateChangeList()
    },
    //导航点击
    navTap(e) {
        var token = wx.getStorageSync("token")
        if (!token) {
            this.setData({
                isLogin: false
            })
            return
        }

        wx.navigateTo({
            url: e.currentTarget.dataset.url
        })

    },
    //弹出积分兑换的页面
    showExchange() {


        // this.setData({
        //         isExchange:false
        //     })

        // wx.hideTabBar()
    },
    /**
     * 跳转新闻详情
     * @param {*} e 
     */
    navNewsDetail() {
        wx.navigateTo({
            url: '/pages/index/news_detail/news_detail',
        })
    },
    /**
     * 跳转商品详情
     * @param {*} e 
     */
    navGoodDetail(e) {
        wx.navigateTo({
            url: '/pages/scoresMall/good_detail/good_detail?id=' + e.currentTarget.dataset.id
        });

    },
    /**
     * 获取分类列表
     * @param {*} e 
     */
    getCateChangeList() {
        var hotGoods = this.data.hotGoods;


        let data = {
            id: this.data.id
        };

        if (data.id == 0) {
            this.getDataList()
            return
        }



        ajaxPost('Goods/goods_category', data, res => {
            console.log(res)

            if (res.code == 0) {

                var data = res.data;
                this.setData({
                    jinyong: true,
                    hotGoods: data.hot_goods,
                    timeGoods: data.limited_time

                })
                wx.hideLoading()
            }

        })
    },
    timeFormat(param) { //小于10的格式化函数
        return param < 10 ? '0' + param : param;
    },
    /**
     * 获取数据
     * @param {*} e 
     */
    getDataList() {
        let endTimeList  = [];
        var token = wx.getStorageSync("token");
        ajaxPost('goods/index', {}, res => {
            console.log(res)
            if (res.code == 0) {


                var data = res.data

                for(var i = 0;i<data.time_goods.length;i++){
                    data.time_goods[i].daojishi = formatTime(new Date(data.time_goods[i].end_time*1000))
                    
                }
                data.time_goods.forEach(o=>{
                    endTimeList.push(o.daojishi)
                })

                // console.log(data.time_goods)

                this.setData({
                    hotGoods: data.hot_goods,
                    timeGoods: data.time_goods,
                    bannerUrls: data.mall_album,
                    top_banner: data.top_banner,
                    mid_banner: data.mid_banner,
                    actEndTimeList: endTimeList
                })
                this.countDown()
                const pages = []
                data.goods_category.forEach((item, index) => {
                    const page = Math.floor(index / 10)
                    if (!pages[page]) {
                        pages[page] = []
                    }
                    pages[page].push(item)
                })
                this.setData({
                    tabList: pages
                })

                wx.hideLoading()
                return




            }
        })
    },
    
    countDown() { //倒计时函数
        // 获取当前时间，同时得到活动结束时间数组
        let newTime = new Date().getTime();
        let actEndTimeList = this.data.actEndTimeList;
        let countDownArr = [];
        let timeGoods = this.data.timeGoods;

        // 对结束时间进行处理渲染到页面
        actEndTimeList.forEach(o => {
            let endTime = new Date(o).getTime();
            
            let obj = null;
            // 如果活动未结束，对时间进行处理
            if (endTime - newTime > 0) {
                let time = (endTime - newTime);
                time = time / 1000;
                // 获取天、时、分、秒
                let day = parseInt(time / (60 * 60 * 24));
                let hou = parseInt(time % (60 * 60 * 24) / 3600);
                let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
                let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
                obj = {
                    day: this.timeFormat(day),
                    hou: this.timeFormat(hou),
                    min: this.timeFormat(min),
                    sec: this.timeFormat(sec)
                }
                
            } else { //活动已结束，全部设置为'00'
                // obj = {
                //     day: '00',
                //     hou: '00',
                //     min: '00',
                //     sec: '00'
                // }

                this.getDataList()
            }
            countDownArr.push(obj)
            // timeGoods.forEach(o=>{
            //     o.date = obj
            // })
            // countDownArr.push(obj);
            for(let i = 0;i<timeGoods.length;i++){
                timeGoods[i].date = countDownArr[i]
            }
            // timeGoods.push(obj)
        })
        // 渲染，然后每隔一秒执行一次倒计时函数
        this.setData({
            timeGoods: timeGoods
        })
        setTimeout(this.countDown, 1000);
    },

    /**
     * 跳转h5
     * @param {*} e 
     */
    navh5(e) {
        var url = e.currentTarget.dataset.url;
        if (url.indexOf('/pages/') != -1) {
            wx.navigateTo({
                url: url
            })
        } else {
            wx.navigateTo({
                url: '/pages/h5/h5?url=' + url
            })
        }
    },
    /**
     * 跳转兑换
     * @param {*} e 
     */
    navExchange(e) {
        var token = wx.getStorageSync("token");
        if (!token) {
            this.setData({
                isLogin: false
            })
            return
        } else {
            console.log(e)
            wx.navigateTo({
                url: '/pages/index/scoreExchange/scoreExchange?id=' + e.currentTarget.dataset.id
            })
        }

    },
    /**
     * 查看更多商品
     * @param {*} e 
     */
    lookMore(e) {
        var index = e.currentTarget.dataset.index;

        wx.navigateTo({
            url: '/pages/index/goodsList/goodsList?index=' + index,
        })

    },
    swiperChange: function(e) {
        this.setData({
            currentIndex: e.detail.current
        })
    },

})